import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
const state = {
  token: getToken(),// 设置token为共享状态 初始化vuex的时候 就先从缓存中读取
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token // 获取token  
    // 同步给缓存
    setToken(token)
  },
  removeToken(state) {
    state.token = null // 清空 token
    removeToken() // 清空缓存的 token
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 调用接口
  async setLogin(context, data) {
    // 获取token
    let result = await login(data)
    console.log(result)
    context.commit('setToken', result)
    // 拿到token 证明获取成功，设置当前时间戳
    // setTimeStamp()
  },
  async getUserInfo(context) {
    let result = await getUserInfo()
    let baseInfo = await getUserDetailById(result.userId)
    context.commit('setUserInfo', { ...result, ...baseInfo })
    return result
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  actions,
  mutations
}